/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import domain.EccezioneUpdater;
import domain.Root;
import gui.GUIUtils;
import gui.RootsView;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;

/**
 *
 * @author Alessio
 */
public class RootsController {
    private static RootsController instance = new RootsController();

    public static RootsController getInstance() {
        return instance;
    }
    
    private RootsView view;

    private RootsController() {
    }
    
    public void setView(RootsView view){
        this.view = view;
    }
    
    public void deleteSelectedRoot() {
        try {
            int selectedIndex = view.getRoots().getSelectedIndex();
            Root root = (Root) ((DefaultListModel) view.getRoots().getModel()).get(selectedIndex);
            root.deleteFromDB();
            ((DefaultListModel) view.getRoots().getModel()).remove(selectedIndex);
        } catch (EccezioneUpdater ex) {
            GUIUtils.showError(ex.getMessage());
        }
    }
    public void addRoot() {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.showOpenDialog(null);
        File selectedFile = fc.getSelectedFile();
        if(selectedFile != null){
            try {
                String path = selectedFile.getCanonicalPath();
                Root root = new Root();
                root.setPath(path);
                root.createOnDB();
                ((DefaultListModel)view.getRoots().getModel()).addElement(root);            
            } catch (EccezioneUpdater ex) {
                GUIUtils.showError(ex.getMessage());
            } catch (IOException ex) {
                GUIUtils.showError(ex.getMessage());
            }
        }
    }

    public void read(DefaultListModel model, Collection<Root> allRoots) {
        for (Root r : allRoots) {
            model.addElement(r);
        }
    }
}
